package cn.com.startai.smartadh5.extension.utils.musicplayer;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.support.v4.util.LruCache;
import android.text.TextUtils;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ScreenUtils;

import java.io.FileNotFoundException;
import java.io.InputStream;

import cn.com.startai.smartadh5.R;
import cn.com.startai.smartadh5.db.db.entity.PlayInfo;
import cn.com.startai.smartadh5.main.application.Application;

/**
 * 专辑封面图片加载器
 * Created by wcy on 2015/11/27.
 */
public class CoverLoader {
    public static final int THUMBNAIL_MAX_LENGTH = 500;
    private static final String KEY_NULL = "null";

    // 封面缓存
    private LruCache<String, Bitmap> mCoverCache;
    private Context mContext;
    private int bitmapSize;


    private enum Type {
        THUMBNAIL(""),
        BLUR("#BLUR"),
        ROUND("#ROUND");

        private String value;

        Type(String value) {
            this.value = value;
        }
    }

    public static CoverLoader getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static CoverLoader instance = new CoverLoader();
    }

    private CoverLoader() {
        // 获取当前进程的可用内存（单位KB）
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        // 缓存大小为当前进程可用内存的1/8
        int cacheSize = maxMemory / 8;
        mCoverCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    return bitmap.getAllocationByteCount() / 1024;
                } else {
                    return bitmap.getByteCount() / 1024;
                }
            }
        };
        mContext = Application.getContext();

        bitmapSize = Math.min(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight()) / 2;
    }

    public Bitmap loadThumbnail(PlayInfo music) {
        return loadCover(music, Type.THUMBNAIL);
    }

    public Bitmap loadBlur(PlayInfo music) {
        return loadCover(music, Type.BLUR);
    }

    public Bitmap loadRound(PlayInfo music) {
        return loadCover(music, Type.ROUND);
    }


    private Bitmap loadCover(PlayInfo music, Type type) {
        Bitmap bitmap;
        String key = getKey(music, type);
        if (TextUtils.isEmpty(key)) {
            bitmap = mCoverCache.get(KEY_NULL.concat(type.value));
            if (bitmap != null) {
                return bitmap;
            }

            bitmap = getDefaultCover(type);
            mCoverCache.put(KEY_NULL.concat(type.value), bitmap);
            return bitmap;
        }

        bitmap = mCoverCache.get(key);
        if (bitmap != null) {
            return bitmap;
        }

        bitmap = loadCoverByType(music, type);
        if (bitmap != null) {
            mCoverCache.put(key, bitmap);
            return bitmap;
        }

        return loadCover(null, type);
    }

    private String getKey(PlayInfo music, Type type) {
        if (music == null) {
            return null;
        }

        if (music.getSourceType() == PlayInfo.SOURCE_TYPE_LOCAL) {
            return String.valueOf(music.getFilePath()).concat(type.value);
        } else if (music.getSourceType() == PlayInfo.SOURCE_TYPE_ONLINE && !TextUtils.isEmpty(music.getCoverPath())) {
            return music.getCoverPath().concat(type.value);
        } else {
            return null;
        }
    }

    private Bitmap getDefaultCover(Type type) {
        switch (type) {
            case BLUR:
                return BitmapFactory.decodeResource(mContext.getResources(), R.drawable.bg_music);
            case ROUND:
                //                bitmap = ImageUtils.scale(bitmap, bitmapSize, bitmapSize, true);
                return BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_ablume_default);
            default:
                return BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_ablume_default);
        }
    }

    private Bitmap loadCoverByType(PlayInfo music, Type type) {
        Bitmap bitmap;
        if (music.getSourceType() == PlayInfo.SOURCE_TYPE_LOCAL) {
            bitmap = createAlbumArt(music.getFilePath());
        } else {
            bitmap = loadCoverFromFile(music.getCoverPath());
        }

        switch (type) {
            case BLUR:
                if(bitmap == null) {
                    return null;
                }
                return ImageUtils.stackBlur(bitmap, 70);
            case ROUND:
                return ImageUtils.toRound(bitmap, true);
            default:
                return bitmap;
        }
    }

    /**
     * 从媒体库加载封面<br>
     * 本地音乐
     */
    private Bitmap loadCoverFromMediaStore(long albumId) {
        ContentResolver resolver = mContext.getContentResolver();
//        Uri uri = MusicUtils.getMediaStoreAlbumCoverUri(albumId);
        Uri uri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
        InputStream is;
        try {
            is = resolver.openInputStream(uri);
        } catch (FileNotFoundException ignored) {
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeStream(is, null, options);
    }

    /**
     * 获取专辑封面
     * @param filePath 文件路径，like XXX/XXX/XX.mp3
     * @return 专辑封面bitmap
     */
    public Bitmap createAlbumArt(final String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        //能够获取多媒体文件元数据的类
        try {
            retriever.setDataSource(filePath); //设置数据源
            byte[] embedPic = retriever.getEmbeddedPicture(); //得到字节型数据
            if(embedPic != null) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bitmap = BitmapFactory.decodeByteArray(embedPic, 0, embedPic.length, options); //转换为图片
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 从下载的图片加载封面<br>
     * 网络音乐
     */
    private Bitmap loadCoverFromFile(String path) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        return BitmapFactory.decodeFile(path, options);
    }
}
